package com.github.mall.common.kafka.provider;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSONUtil;
import com.github.mall.common.kafka.entity.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Component;

import java.sql.Timestamp;

@Component
public class KafkaProvider<T> {


    private final KafkaTemplate<String, String> kafkaTemplate;


    private static volatile KafkaProvider kafkaProvider = null;

    @Autowired
    public KafkaProvider(KafkaTemplate kafkaTemplate){
      this.kafkaTemplate = kafkaTemplate;
    }

//    @Bean
//    public static KafkaProvider getKafkaProviderInstance(){
//        if(kafkaProvider == null){
//            synchronized (KafkaProvider.class){
//                if(kafkaProvider == null){
//                    kafkaProvider = new KafkaProvider();
//                }
//            }
//        }
//        return kafkaProvider;
//    }


    public void send(String topic, T msg) {
        Message message = new Message(IdUtil.simpleUUID(), msg, Timestamp.valueOf(DateUtil.now()));
        kafkaTemplate.send(topic, JSONUtil.toJsonStr(message));
    }
}
